/* UI组件交互模块 - 模态框功能 */

/**
 * 初始化模态框功能
 */
export function initModals() {
  const modals = document.querySelectorAll('.modal');
  const modalTriggers = document.querySelectorAll('[data-toggle="modal"]');
  
  // 打开模态框
  modalTriggers.forEach(trigger => {
    trigger.addEventListener('click', function() {
      const targetModalId = this.getAttribute('data-target');
      const targetModal = document.getElementById(targetModalId);
      
      if (targetModal) {
        openModal(targetModal);
      }
    });
  });
  
  // 关闭模态框
  modals.forEach(modal => {
    // 点击关闭按钮
    const closeButton = modal.querySelector('.modal-close');
    if (closeButton) {
      closeButton.addEventListener('click', function() {
        closeModal(modal);
      });
    }
    
    // 点击背景关闭
    const backdrop = modal.querySelector('.modal-backdrop');
    if (backdrop) {
      backdrop.addEventListener('click', function() {
        closeModal(modal);
      });
    }
    
    // ESC键关闭
    modal.addEventListener('keydown', function(e) {
      if (e.key === 'Escape') {
        closeModal(modal);
      }
    });
  });
}

/**
 * 打开模态框
 */
export function openModal(modal) {
  modal.classList.add('show');
  document.body.style.overflow = 'hidden'; // 防止背景滚动
  
  // 添加打开动画
  const modalContent = modal.querySelector('.modal-content');
  if (modalContent) {
    modalContent.style.opacity = '0';
    modalContent.style.transform = 'translateY(-20px)';
    modalContent.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
    
    setTimeout(() => {
      modalContent.style.opacity = '1';
      modalContent.style.transform = 'translateY(0)';
    }, 10);
  }
}

/**
 * 关闭模态框
 */
export function closeModal(modal) {
  const modalContent = modal.querySelector('.modal-content');
  
  if (modalContent) {
    modalContent.style.opacity = '0';
    modalContent.style.transform = 'translateY(-20px)';
    
    setTimeout(() => {
      modal.classList.remove('show');
      document.body.style.overflow = ''; // 恢复背景滚动
    }, 300);
  } else {
    modal.classList.remove('show');
    document.body.style.overflow = '';
  }
}